package org.ws.httphelper.support.pipeline.handler.request;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.ws.httphelper.common.Constant;
import org.ws.httphelper.core.pipeline.HandlerOrder;
import org.ws.httphelper.core.pipeline.RequestHandler;
import org.ws.httphelper.exception.RequestException;
import org.ws.httphelper.model.RequestContext;
import org.ws.httphelper.model.config.RequestConfig;
import org.ws.httphelper.model.http.ContentType;
import org.ws.httphelper.model.http.RequestData;

import java.util.Map;

@HandlerOrder(value = 2,level = HandlerOrder.OrderLevel.SYSTEM)
public class BuildHeaderHandler implements RequestHandler {

    private static Logger log = LoggerFactory.getLogger(BuildHeaderHandler.class.getName());

    @Override
    public boolean handler(RequestContext requestContext) throws RequestException {
        RequestConfig requestConfig = requestContext.getRequestConfig();
        ContentType contentType = requestConfig.getContentType();
        Map<String, String> defaultCookers = requestConfig.getDefaultCookers();
        Map<String, String> defaultHeaders = requestConfig.getDefaultHeaders();
        RequestData requestData = requestContext.getRequestData();
        if(requestData.getContentType() == null && contentType != null){
            requestData.setContentType(contentType);
        }
        else {
            contentType = requestData.getContentType();
        }
        Map<String, String> headers = requestData.getHeaders();
        if(contentType != null && !headers.containsKey(Constant.HEAD_CONTENT_TYPE)){
            headers.put(Constant.HEAD_CONTENT_TYPE,contentType.getType());
        }
        if(MapUtils.isNotEmpty(defaultCookers)){
            StringBuilder cookies = new StringBuilder();
            for (Map.Entry<String, String> entry : defaultCookers.entrySet()) {
                cookies.append(entry.getKey()).append("=").append(entry.getValue()).append(";");
            }
            defaultHeaders.put("Cookie",cookies.toString());
        }
        if(MapUtils.isNotEmpty(defaultHeaders)){
            for (Map.Entry<String, String> entry : defaultHeaders.entrySet()) {
                if (!headers.containsKey(entry.getKey())) {
                    headers.put(entry.getKey(),entry.getValue());
                }
            }
        }
        if(log.isDebugEnabled()){
            log.debug(JSON.toJSONString(headers, SerializerFeature.PrettyFormat));
        }
        return true;
    }
}
